package com.tc.travel.submitter.executor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tc.travel.submitter.pojo.VisaForImportReturnReportDto;
import com.tc.travel.submitter.pojo.VisaForImportReturnReportVisitorDto;
import com.tc.travel.submitter.service.ReturnReportBo;
import com.tc.travel.util.Consts;
import com.tc.travel.util.HtmlUtil;
import com.tc.travel.util.HttpClientUtil;
import com.tc.travel.util.PropertyUtil;
import com.tc.travel.util.SleepUtil;
import com.tc.travel.util.StringUtil;
import com.tc.travel.util.exception.ComRuntimeException;

@Component
public class ReturnReportAddOneByOneExecutor extends BaseExecutor {
	private static Logger log = Logger.getLogger(ReturnReportAddOneByOneExecutor.class);

	@Autowired
	private ReturnReportBo returnReportBo;

	public void execute() {
		try {
			VisaForImportReturnReportDto visaDto = returnReportBo.getVisaForImportReturnReport();
			if (visaDto != null) {
				String cookie = sessionBo.getCookie();
				log.info("cookie:" + cookie);

				int returnReportState;
				String errorMsg;

				try {
					log.info("step1.openSearchVisaPage...");
					openSearchVisaPage(cookie);

					log.info("step2.getVisaIdentityId-->dest_visa_id:" + visaDto.getDestVisaId() + "...");
					SleepUtil.sleepRandom(3, 6);
					String visaIdentityId = getVisaIdentityId(visaDto.getDestVisaId(), cookie);
					log.info("visaIdentityId:" + visaIdentityId);

					log.info("step3.openPersonListLoginPage...");
					SleepUtil.sleepRandom(1, 3);
					openPersonListLoginPage(visaIdentityId, cookie);

					List<VisaForImportReturnReportVisitorDto> visitorList = visaDto.getVisitorList();
					for (VisaForImportReturnReportVisitorDto visitorDto : visitorList) {
						log.info("step4.点“新规登录”按钮...");
						SleepUtil.sleepRandom(1, 3);
						String pageKey = clickAddPersonButton(visaIdentityId, cookie);

						log.info("step5.点“确认”按钮提交...");
						SleepUtil.sleepRandom(10, 20);
						pageKey = clickSubmitButton(visaIdentityId, visitorDto, pageKey, cookie);

						log.info("step6.点“登录”按钮...");
						SleepUtil.sleepRandom(1, 3);
						confirmSubmit(visaIdentityId, pageKey, cookie);
					}

					// 更新状态为成功
					returnReportState = Consts.RETURN_REPORT_STATE_IMPORT_SUCC;
					errorMsg = "";
				} catch (Throwable e) {
					returnReportState = Consts.RETURN_REPORT_STATE_IMPORT_FAIL;
					errorMsg = e.getMessage();
					log.error("import return report error. visa_info_id=" + visaDto.getVisaInfoId(), e);
				}

				log.info("updateReturnReportState:");
				returnReportBo.updateReturnReportState(visaDto.getVisaInfoId(), returnReportState, errorMsg);
			}
		} catch (Throwable e) {
			log.error("ReturnReportAddOneByOneExecutor error: " + e.getMessage(), e);
		}
	}

	// step3. 点“个人名簿登录”按钮
	private void openPersonListLoginPage(String identityId, String cookie) {
		String url = PropertyUtil.destUrlIdentityNameList;

		Map<String, String> params = new HashMap<String, String>();
		params.put("IDENTITY_ID", identityId);

		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Cookie", cookie);
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		headers.put("Accept-Encoding", "gzip, deflate, sdch, br");
		headers.put("Accept-Language", "en-US,en;q=0.8,ja;q=0.6");
		headers.put("Connection", "keep-alive");
		headers.put("Host", "churenkyosystem.com");
		headers.put("Referer", "https://churenkyosystem.com/member/identity_list.php");
		headers.put("Upgrade-Insecure-Requests", "1");
		headers.put("User-Agent", Consts.USER_AGENT);

		HttpClientUtil.doGet(url, params, headers);
	}

	// step4.点“新规登录”按钮...
	private String clickAddPersonButton(String identityId, String cookie) {
		String url = PropertyUtil.destUrlIdentityNameEdit;

		Map<String, String> params = new HashMap<String, String>();
		params.put("mode", "add");
		params.put("IDENTITY_ID", identityId);

		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Cookie", cookie);
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		headers.put("Accept-Encoding", "gzip, deflate, sdch, br");
		headers.put("Accept-Language", "en-US,en;q=0.8,ja;q=0.6");
		headers.put("Connection", "keep-alive");
		headers.put("Host", "churenkyosystem.com");
		headers.put("Referer", "https://churenkyosystem.com/member/identity_name_list.php?IDENTITY_ID=" + identityId + "&SORT=2&ret=1");
		headers.put("Upgrade-Insecure-Requests", "1");
		headers.put("User-Agent", Consts.USER_AGENT);

		String html = HttpClientUtil.doGet(url, params, headers);
		assertAddPersonPage(html);

		String pageKey = HtmlUtil.getPageKey(html);
		if (StringUtil.isEmpty(pageKey)) {
			throw new ComRuntimeException("clickAddPersonButton error; no page key found.");
		}

		return pageKey;
	}

	private void assertAddPersonPage(String html) {
		if (StringUtil.isEmpty(html)) {
			throw new ComRuntimeException("clickAddPersonButton error; returned html is null.");
		}

		// if (html.indexOf("身元保証書発行内容") < 0 || html.indexOf("確認画面") < 0 || html.indexOf("査証種別") < 0) {
		// throw new ComRuntimeException("clickUploadButton error; html content error.");
		// }
	}

	// step5.点“确认”按钮提交...
	private String clickSubmitButton(String identityId, VisaForImportReturnReportVisitorDto visitorDto, String pageKey, String cookie) {
		String url = PropertyUtil.destUrlIdentityNameEdit + "?mode=add&IDENTITY_ID=" + identityId;

		Map<String, String> params = new HashMap<String, String>();
		params.put("NAME", visitorDto.getName());
		params.put("NAME_PINYIN", visitorDto.getPinyinName());
		params.put("SEX", visitorDto.getSex());
		params.put("ADDRESS", visitorDto.getPermanentCity());
		params.put("BIRTH_Y", visitorDto.getBirthdayYyyy());
		params.put("BIRTH_M", visitorDto.getBirthdayMm());
		params.put("BIRTH_D", visitorDto.getBirthdayDd());
		params.put("PASSPORT_NO", visitorDto.getPassport());
		params.put("MEMO", visitorDto.getComment());
		params.put("_PAGE_KEY", pageKey);
		params.put("BTN_CHECK_x", "確認");

		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Cookie", cookie);
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		headers.put("Accept-Encoding", "gzip, deflate, br");
		headers.put("Accept-Language", "en-US,en;q=0.8,ja;q=0.6");
		headers.put("Cache-Control", "max-age=0");
		headers.put("Connection", "keep-alive");
		headers.put("Host", "churenkyosystem.com");
		headers.put("Origin", "https://churenkyosystem.com");
		headers.put("Referer", "https://churenkyosystem.com/member/identity_name_edit.php?mode=add&IDENTITY_ID=" + identityId);
		headers.put("Upgrade-Insecure-Requests", "1");
		headers.put("User-Agent", Consts.USER_AGENT);

		String html = HttpClientUtil.doPost(url, params, headers);
		assertConfirmPage(html);

		String confirmPageKey = HtmlUtil.getPageKey(html);
		if (StringUtil.isEmpty(confirmPageKey)) {
			throw new ComRuntimeException("clickSubmitButton error; no page key found.");
		}

		return confirmPageKey;
	}

	private void assertConfirmPage(String html) {
		if (StringUtil.isEmpty(html)) {
			throw new ComRuntimeException("clickSubmitButton error; returned html is null.");
		}

		if (html.indexOf("身元保証書名簿") < 0 || html.indexOf("確認画面") < 0 || html.indexOf("備考") < 0) {
			throw new ComRuntimeException("clickUploadButton error; html content error.");
		}
	}

	// 点“确认”按钮
	private void confirmSubmit(String identityId, String pageKey, String cookie) {
		String url = PropertyUtil.destUrlIdentityNameEdit + "?mode=add&IDENTITY_ID=" + identityId;

		Map<String, String> params = new HashMap<String, String>();
		params.put("_PAGE_KEY", pageKey);
		params.put("BTN_CHECK_SUBMIT_x", "登 録");

		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Cookie", cookie);
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		headers.put("Accept-Encoding", "gzip, deflate, br");
		headers.put("Accept-Language", "en-US,en;q=0.8,ja;q=0.6");
		headers.put("Cache-Control", "max-age=0");
		headers.put("Connection", "keep-alive");
		headers.put("Host", "churenkyosystem.com");
		headers.put("Origin", "https://churenkyosystem.com");
		headers.put("Referer", "https://churenkyosystem.com/member/identity_name_edit.php?mode=add&IDENTITY_ID=" + identityId);
		headers.put("Upgrade-Insecure-Requests", "1");
		headers.put("User-Agent", Consts.USER_AGENT);

		String html = HttpClientUtil.doPost(url, params, headers);
		assertConfirmResultPage(html);
	}

	private void assertConfirmResultPage(String html) {
		if (StringUtil.isEmpty(html)) {
			throw new ComRuntimeException("confirmSubmit error; returned html is null.");
		}

		// if (html.indexOf("身元保証書発行内容") < 0 || html.indexOf("確認画面") < 0 || html.indexOf("査証種別") < 0) {
		// throw new ComRuntimeException("clickUploadButton error; html content error.");
		// }
	}

}
